<template>
  <div class="">

    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="listid">
            <el-button slot="append" @click="searchUser" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserList">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <template>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="id" width="180">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="mobile" label="电话">
          </el-table-column>
          <el-table-column prop="email" label="邮箱">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <!-- 作用域插槽 可以拿到每一行的数据对象 -->
            <template slot-scope="scope">
              <el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-tooltip class="item" effect="dark" content="修改" placement="top">
                <el-button @click="setUserResult(scope.row)" type="primary" icon="el-icon-edit" size='mini'></el-button>
              </el-tooltip>
              <!-- 删除 -->
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button type="danger" @click="deleteUser(scope.row.id)" icon="el-icon-delete" size='mini'>
                </el-button>
              </el-tooltip>
              <!-- 分配角色 -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                <el-button type="warning" @click="allotUserDialog(scope.row.id)" icon="el-icon-setting" size='mini'>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1"
          :page-sizes="[2, 3, 5, 7]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="20">
        </el-pagination>
      </div>
    </el-card>
    <!--新增dialog弹窗  -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form label-width="80px" :rules="rules" ref="addForm" :model="addForm">

        <el-form-item label="账号" prop="username">
          <el-input placeholder="请输入用户名" v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="addForm.password">
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="addForm.email">
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="addForm.mobile">
          </el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- dialog弹窗end -->
    <!-- 修改dialog -->
    <el-dialog title="修改" width="30%" :visible.sync="setDialogVisible">
      <el-form label-width="80px" :rules="rules" ref="editForm" :model="editForm">

        <el-form-item label="用户名" prop="name">
          <el-input placeholder="请输入用户名" disabled v-model="editForm.username">
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="editForm.email">
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="editForm.mobile">
          </el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">

        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserResult">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改dialog -->
    <!-- 分配角色dialog -->
    <el-dialog title="提示" :visible.sync="allotUserdialogVisible" width="30%" :before-close="allotUserhandleClose">

      <el-select v-model="userValue" placeholder="请选择" @change="selectAllotUser">
        <el-option v-for="item in userList" :key="item.id" :label="item.roleName" :value="item.id">
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allotUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAllotUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->


  </div>
</template>

<script>
  export default {
    components: {},
    data() {
      var checkEmail = (rule, value, cb) => {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (regEmail.test(value)) {
          return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的邮箱'))
      }
      //验证手机号码的规则
      var checkMobile = (rule, value, cb) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的手机号码'))
      }
      return {
        tableData: [{
          id: '',
          username: '',
          mobile: ''
        }],
        queryInfo: {
          pagenum: 1,
          pagesize: 2
        },
        listid: '',
        // 新增
        dialogVisible: false,
        // 修改
        setDialogVisible: false,
        // 分配权限dialog
        allotUserdialogVisible: false,
        // 添加数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        editForm: {
          name: '',
          email: '',
          mobile: ''
        },
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 8,
              message: '长度在 3 到 8 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 8,
              message: '长度在 3 到 8 个字符',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              message: '邮箱格式不正确，请重新输入',
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              message: '手机号码不正确，请重新输入',
              trigger: 'blur'
            }
          ]
        },
        value: true,
        // 角色列表
        userList: [],
        userValue: '',
        // 角色id
        rid: '',
        // 用户id
        id: ''
      }
    },
    created() {
      this.getData()
    },
    mounted() {},
    watch: {},
    computed: {},
    methods: {
      // 初始化数据
      getData: function () {
        this.$axios.get('users', {
          params: this.queryInfo
        }).then(val => {
          this.tableData = val.data.users
          console.log(val.data.users);
        })
      },
      //   分页
      handleSizeChange(page) {
        this.queryInfo.pagesize = page
        this.getData()
      },
      handleCurrentChange(page) {
        this.queryInfo.pagenum = page
        this.getData()
        console.log(this.tableData);
      },
      //   搜索
      searchUser() {
        this.$axios.get('users/' + this.listid).then(val => {
          this.tableData = []
          this.tableData[0] = val.data
        })
      },
      //   添加数据-弹窗
      addUserList() {
        this.dialogVisible = true
      },
      //   添加数据
      setUserData() {
        this.$refs.addForm.validate(val => {

          if (!val) {
            return this.$message.error('输入的格式有误')
          }
          console.log(this.addForm);
          this.$axios.post('users', {
            username: this.addForm.username,
            password: this.addForm.password,
            email: this.addForm.email,
            mobile: this.addForm.mobile,
          }).then(val => {
            this.getData()
            this.dialogVisible = false
            console.log(val);
            this.$message('添加成功')
          })

        })

      },
      // 更改状态
      userStateChanged(val) {
        this.$axios.put('users/' + val.id + '/state/' + val.mg_state).then(val => {

        })
      },
      // 打开编辑用户提交
      setUserResult(val) {
        this.setDialogVisible = true
        this.editForm = val
      },
      // 编辑请求
      editUserResult() {
        this.$refs.editForm.validate(val => {
          if (!val) {
            return this.$message.error('格式有误!')
          }
          this.$axios.put('users/' + this.editForm.id,
            this.editForm
          ).then(val => {

            if (val.meta.status != 200) {
              return this.$message.error('修改失败!')
            }
            this.$message.success('修改成功!')
          })
          this.setDialogVisible = false
        })

      },
      // 删除
      deleteUser(id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.delete('users/' + id).then(val => {
            if (val.meta.status != 200) {
              return this.$message.error('删除失败!')
            }
            this.$message.success('删除成功!')
            this.getData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 打开分配角色dialog
      allotUserDialog(id) {
        this.id = id
        this.allotUserdialogVisible = true
        this.$axios.get('roles').then(val => {
          this.userList = val.data
          console.log(this.userList);
        })
      },
      allotUserhandleClose() {},
      // 下拉框选择角色
      selectAllotUser(id) {
        this.rid = id

      },
      // 提交分配角色
      submitAllotUser() {
        this.$axios.put('users/' + this.id + '/role', {
          rid: this.rid
        }).then(val => {
          if (val.meta.status != 200) {
            return this.$message.error(val.meta.msg)
          }
          this.$message.success(val.meta.msg)
        })
        this.allotUserdialogVisible = false
      }
    },
  }

</script>
<style lang="css" scoped>
</style>
